package LockTest;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class InterruptTest {

    private static final Logger logger = LoggerFactory.getLogger(InterruptTest.class);

    @Test
    public void testInterrupt() throws InterruptedException {
        Object o = new Object();
        Thread threadA = new Thread(() -> {
            logger.info("threadA park");
            LockSupport.park(o);
            logger.info("threadA unPark");
            logger.info("threadA wait begin ");
            synchronized (Thread.currentThread()) {
                try {
                    Thread.currentThread().wait();
                    logger.info("threadA wait end ");
                    logger.info(String.valueOf(Thread.interrupted()));
                    TimeUnit.SECONDS.sleep(2);
                    logger.info(String.valueOf(Thread.interrupted()));
                } catch (InterruptedException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        });
        threadA.start();
        TimeUnit.SECONDS.sleep(2);
        LockSupport.unpark(threadA);
        TimeUnit.SECONDS.sleep(2);
        threadA.interrupt();
        synchronized (threadA) {
            threadA.notify();
        }
        TimeUnit.SECONDS.sleep(1);
        // sleep的时候调用interrupt会导致线程抛InterruptedException，从而达到中断的目的
        threadA.interrupt();
        TimeUnit.SECONDS.sleep(3);
    }

}
